package com.bs.manager05.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.bs.manager05.entity.Menu;
import com.bs.manager05.entity.Role;
import com.bs.manager05.entity.User;
import com.bs.manager05.service.IMenuService;
import com.bs.manager05.service.IRoleService;
import com.bs.manager05.service.IUserService;
import com.bs.manager05.service.IUserroleService;
import com.bs.manager05.utils.*;
import com.bs.manager05.utils.auth.Auth;
import com.bs.manager05.utils.exception.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author yao
 * @since 2022-12-18
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户系统管理")
public class UserController {
    @Resource
    IUserService service;

    @Resource
    IUserroleService service1;

    @Resource
    IRoleService service2;

    @Resource
    IMenuService service3;

    @Resource
    RedisUtils utils;

    String slat="baisi";


    @GetMapping
    @ApiOperation("用户分页条件查询")
    //@Auth
    public Result index(@RequestParam(defaultValue = "1") @ApiParam("当前页") Integer pageNum, @ApiParam("页面大小") @RequestParam(defaultValue = "5") Integer pageSize, @ApiParam("用户名") @RequestParam(defaultValue = "") String name){
        Page<User> page=new Page<User>(pageNum,pageSize);
        LambdaQueryWrapper<User> lq=new LambdaQueryWrapper<>();
        lq.like(StringUtils.isNotBlank(name),User::getUsername,name);
        page=service.page(page,lq);
        return Result.success(page);
    }

    @PostMapping
    @ApiOperation("用户添加")
    public Result add(@RequestBody @ApiParam("用户表") User menu){
        boolean save = service.save(menu);
        if(save){
            return Result.success("用户添加成功");
        }else{
            return Result.fail("用户添加失败");
        }
    }

    @GetMapping("/{id}")
    @ApiOperation("根据用户id查询用户")
    @Auth("system:user")
    public Result getById(@PathVariable("id") @ApiParam("用户id") String id){
        User menu = service.getById(id);
        return Result.success(menu);
    }

    @PutMapping
    @ApiOperation("用户修改")
    @Auth("system:user:update")
    public Result update(@RequestBody @ApiParam("用户表")User menu){
        boolean update = service.updateById(menu);
        if(update){
            return Result.success("用户修改成功");
        }else{
            return Result.fail("用户修改失败");
        }
    }

    @DeleteMapping("/{id}")
    @ApiOperation("用户删除")
    @Auth("system:user:del")
    public Result del(@PathVariable("id") @ApiParam("用户id") String id){
        boolean del = service.removeById(id);
        if(del){
            return Result.success("用户删除成功");
        }else{
            return Result.fail("用户删除失败");
        }
    }

    @PutMapping("/addRoles")
    @ApiOperation("给用户添加对应的角色")
    public Result addRoles(@ApiParam("用户id") @RequestParam String userid,@ApiParam("角色id") @RequestParam String[] roleids){
        int row = service1.addRoles(userid, roleids);
        if(row>0){
            return Result.success("成功");
        }else{
            return Result.fail("失败");
        }
    }

    /*@PostMapping("/login")
    @ApiOperation("用户登录")
    public Result login(@ApiParam("用户名") @RequestParam String username,@ApiParam("用户密码") @RequestParam String pwd, HttpServletRequest request){
        HttpSession session = request.getSession();
        //判断用户名是否为空
        if(StringUtils.isNotBlank(username)){
           LambdaQueryWrapper<User> lq=new LambdaQueryWrapper<>();
           lq.eq(User::getUsername,username);
            User user = service.getOne(lq);
            if(user!=null){
               if(StringUtils.isNotBlank(pwd)){
                   if(MD5SaltUtils.equals(pwd,slat,user.getPwd())){
                     if(user.getStatus()==1){
                         throw new NoStatusException("该用户被冻结");
                      }else if(user.getStatus()==2){
                         throw new NoStatusException("该用户被注销");
                     }
                     //用户登录成功后，展示该用户的菜单列表
                       //查询该用户所对应的角色
                       List<Role> roles = service2.getRoles(user.getUserid());
                      user.setRoles(roles);
                       //查询该用户对应的菜单列表
                       List<Menu> menus = service3.getMenus(user.getUserid(), "0");
                       user.setMenus(menus);
                       //查询该用户对应的菜单权限
                       List<String> premission = service3.getPremission(user.getUserid());
                       Set<String> sets=new HashSet<>(premission);
                       user.setPremission(sets);
                       //将登录的用户信息结合token和redis进行存储
                       String token = UUIDFactory.UUID();
                       utils.set(token,user,TokenUtils.TOKEN_TIME);
                       Map<String,Object> map=new HashMap<>();
                       map.put("token",token);
                       map.put("user",user);
                       return Result.success(map);
                   }else{
                       throw new PasswordEqualException("用户密码不正确");
                   }
               }else{
                   throw new PasswordNullException("用户密码为空");
               }
            }else{
                throw new NoUserException("该用户信息不存在");
            }
        }else{
         throw new NotUserNullException("用户名不能为空");
        }
    }
*/

    @PostMapping("/login")
    public Result login(@RequestBody User user){
        String token = service.login(user);

        return Result.success(token);
    }
     @GetMapping("/getUser")
    public Result getUser(HttpServletRequest request){
        //HttpSession session = request.getSession();
        //User user = (User)session.getAttribute("user");
        String header = request.getHeader(TokenUtils.TOKEN);
        if(StringUtils.isBlank(header)){
            throw new NoUserException("您还未登录,请登录后再访问");
        }
        User user =(User) utils.get(header);
        if(user!=null){
          return Result.success(user);
        }else{
            return Result.fail("你还未登录,请登录后再访问");
        }
    }
}

